import React, { Component } from 'react';
import moment from 'moment'
import Table from "bee-table";
import 'bee-table/build/Table.css';
import { FormControl, Select } from 'tinper-bee';
const Option = Select.Option;
import YGCupload from '../../../components/YGCCreateUpload'
import createYGCPage from '../../../components/CreateYGCPage/index.jsx'
import billIcon from './../../../assets/icon/ygc_stop_work.png';
import './index.less';
import { loadWorkqualityDetail, getReportById, saveWrokStartReport } from '../workStartReport.config.js'
import buttonClick from '../buttonEvent.js';

let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
	tenantId = cookieStr.split('=')[1];
}

tenantId = tenantId || 'x61tnmfx';

const btnState = {
	ADD: 'add',
	BROWSE: 'browse'
}

const btnCardTpl = {
	[btnState.ADD]: [
		{
			key: 'save',
			name: "提交",
			colors: "primary"
		},
		{
			key: 'cancel',
			name: "取消"
		}
	],
	[btnState.BROWSE]: [
		{
			key: 'add',
			name: '新增',
			colors: "primary"
		},
		{
			key: 'print',
			name: '打印'
		},
		{
			key: 'approveDes',
			name: '审批详情'
		},
		{
			key: 'approve',
			name: '审批'
		},
		{
			key: 'attachment',
			name: '附件'
		},
		{
			key: 'refresh',
			name: '刷新'
		},
	]
}

class WorkStartReportCard extends Component {
	constructor(props) {
		super(props);
		let _me = this;
		this.state = {
			workStartCheckVOS: [],
			cardState: '',
			pk: '',
			formData: {},
		};
		this.formItems = {
			items: [
				{
					attrcode: 'pkProject',
					label: '项目编码',
					required: true,
					itemtype: 'refer',
					refType: 'grid',
					reqRef: {
						columns: [
							{ title: '项目编码', key: 'scode' },
							{ title: '项目名称', key: 'sname' },
						],
						refPk: 'pkProject',
						refUrl: '/projectInTeam/list',
						refMethod: 'get',
						resultPath: 'objects',
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'scode',
						fieldValued: 'pkProject',
						refQueryCondition: () => {
							return {
								pkTenant: tenantId,
								projectState: '-1,0',
								// projectState:''
							}
						},
						filterColumn: ['sname', 'scode'],
					}
				},
				// {
				// 	attrcode: 'aaa',
				// 	label: "项目组织",
				// 	itemtype: "refer",
				// 	refType: 'tree',
				// 	reqRef: {
				// 		refPk: 'pkOrganization',
				// 		queryCondition: function () {

				// 			return { pkTenant: tenantId }
				// 		},
				// 		method: 'get',
				// 		refUrl: "/organization/getPermOrgByUser",
				// 		isMultiSelectedEnabled: false,
				// 		nameField: 'sname',
				// 		codeField: 'scode',
				// 		valueField: 'pkOrganization'
				// 	},
				// },
				{
					attrcode: 'projectCode',
					label: '项目名称',
					required: true,
					disabled: true,
				},
				{
					attrcode: 'orgName',
					label: '项目组织',
					disabled: true,
				},
				{
					attrcode: 'position',
					label: '地理位置',
					visibleEdit: false,
				},
				{
					attrcode: 'pkEnterprise',
					label: '施工单位',
					required: true,
					itemtype: 'refer',
					refType: 'grid',
					reqRef: {
						columns: [
							{ title: '施工单位名称', key: 'enterpriseName' },
						],
						refPk: 'pkEnterprise',
						refUrl: '/team/constructionUnits',
						refMethod: 'get',
						refQueryCondition: () => {
							let project = this.props.form.getFormItemValue('pkProject');
							return { projectid: project && project.value }
						},
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'enterpriseName',
						fieldValued: 'pkEnterprise',
					}
				},
				{
					attrcode: 'pkSupervision',
					label: '监理单位',
					itemtype: 'refer',
					refType: 'grid',
					reqRef: {
						columns: [
							{ title: '监理单位名称', key: 'enterpriseName' },
						],
						refPk: 'pkEnterprise',
						refUrl: '/team/supervisionUnits',
						refMethod: 'get',
						refQueryCondition: () => {
							let project = this.props.form.getFormItemValue('pkProject');
							return { projectid: project && project.value }
						},
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'enterpriseName',
						fieldValued: 'pkEnterprise',
					}
				},
				{
					attrcode: 'pkWorkquality',
					label: '开工条件',
					required: true,
					itemtype: 'refer',
					refType: 'grid',
					isnextrow: false,
					reqRef: {
						columns: [
							{ title: '开工条件', key: 'checkname' },
						],
						refPk: 'pkWorkquality',
						refUrl: '/workquality/searchWeb',
						refMethod: 'get',
						isMultiSelectedEnabled: false,
						fieldDisplayed: 'checkname',
						fieldValued: 'pkWorkquality',
						refQueryCondition: () => {
							return {
								tenantId: tenantId,
								billType: 'KGBG',
							}
						},
					}
				},
				{
					attrcode: 'startdate',
					label: '开工日期',
					itemtype: 'date',
					required: true,
					defaultValue: { value: moment(new Date()) }
				},
				{
					attrcode: 'status',
					label: '单据状态',
					required: false,
					disabled: true,
					placeholder: '自由态'
				},
			],
			afterEvent: (attrcode, oldvalue, value) => {
				if (attrcode == 'pkProject') {
					this.props.form.setFormItemsValue({
						'projectCode': { value: value.record && value.record.sname },
						'orgName': { value: value.record && value.record.orgName },
					});
				} else if (attrcode == 'pkWorkquality') {
					if (value.value) {
						loadWorkqualityDetail({ pkWorkquality: value.value },
							res => {
								res = res.data;
								if (res.resultCode == 'ok') {
									let workStartCheckVOS = res.result.itemtabledata;
									this.setState({
										workStartCheckVOS,

									});
								} else {

								}
							},
							error => { }
						);
					} else {
						this.setState({
							workStartCheckVOS: [],
						});
					}
				}
			}
		};
		this.columns = [
			{
				title: "序号", dataIndex: "index", key: "index", width: '50',
				render(text, record, index) {
					return (
						index + 1
					)
				}
			},
			{ title: "开工条件名称", dataIndex: "checkitem", key: "checkitem", width: '15%' },
			{ title: "条件描述", dataIndex: "checkdescription", key: "checkdescription", width: '30%' },
			{
				title: "结果", dataIndex: "qualification", key: "qualification", width: '10%',
				render(text, record, index) {
					return (_me.state.cardState == 'add' ?
						< Select
							onChange={_me.handleResultChange.bind(_me, record, index)}
						>
							<Option value="1">具备</Option>
							<Option value="2">不具备</Option>
							<Option value="3">不适用</Option>
						</Select >
						:
						<div>{record.qualificationName}</div>)
				}
			},
			{
				title: "结果说明", dataIndex: "instruction", key: "instruction", width: '40%',
				render(text, record, index) {
					return (_me.state.cardState == 'add' ?
						<FormControl
							className={'table-input-textarea ' + (record.hasError ? ' error-border ' : '')}
							// placeholder={placeholder || `请输入${label}`}
							// disabled={disabled}
							bordered
							value={record.instruction}
							onChange={_me.setinstruction.bind(_me, record, index)}
							componentClass='textarea'
						/> :
						<div>{record.instruction}</div>
					)
				}
			}
		];
	}
	componentDidMount() {
		let {
			state: {
				cardState = 'add',
				pk,
			} = {}
		} = this.props.location;
		this.setState({
			cardState,
			pk,
		})
	}
	componentWillUnmount() {
	}

	getPageData = () => {
		getReportById({ reportId: this.state.pk },
			res => {
				res = res.data;
				if (res.resultCode == 'ok') {
					let result = res.result;
					this.props.vendorsSuccess({ 'text': '查询成功' });
					let {
						pkWorkstartreport,
						position,
						pkEnterprise,
						pkSupervision,
						startdate,
						billstatus,
						creator,
						creationtime,
						pkTenant,
						pkWorkquality,
						pkProject,
						projectCode,
						projectName,
						conditionName,
						workqualityVOS,
						pictures,
						// workStartCheckVOS: [{ changeFlag: "29c748d3-00f1-469d-b782-a299ba3cea34", dr: 0, assignInfo: null, … }, …]
						enterpriseName,
						supervisionName,
						status,
						workqualityCount,
						checkCount,
						orgName,
						creatorName,
						strBillstatus,
						pkOrganization,
						pkOrgName,
						pkOrgSrc,
						canApprove,
					} = result;
					// let workStartCheckVOS = res.result.itemtabledata;
					// this.props.form.setFormItemsValue({
					// 	pkProject: { value: projectName },
					// 	projectCode: { value: projectCode },
					// 	orgName: { value: orgName },
					// 	position: { value: position },
					// 	pkEnterprise: { value: enterpriseName },
					// 	pkSupervision: { value: supervisionName },
					// 	pkWorkquality: { value: conditionName },
					// 	startdate: { value: startdate },
					// 	billstatus: { value: status },
					// });
					this.props.form.setFormValue(result, {
						pkProject: projectName,
						pkEnterprise: enterpriseName,
						pkSupervision: supervisionName,
						pkWorkquality: conditionName,
					})
					result.workStartCheckVOS.forEach(cur => {
						cur.checkdescription = cur.description;
						cur.checkitem = cur.checkName;
					})
					if (billstatus === 7 || billstatus === 5) {
						this.props.button.setButtonDisable('approve', false);
					} else {
						this.props.button.setButtonDisable('approve', true);
					}
					// if (!canApprove) {
					// 	this.props.button.setButtonDisable('approve', true);
					// } else{
					// 	this.props.button.setButtonDisable('approve', false);
					// }
					this.setState({
						workStartCheckVOS: result.workStartCheckVOS,
						formData: result,
					});
				} else {

				}
			},
			error => { }
		);
	}
	componentDidUpdate(prevProps, prevState, snapshot) {
		if (prevState.cardState !== this.state.cardState) {
			this.props.button.setButtonState(this.state.cardState);
			this.props.form.setFormStatus(this.state.cardState);
			if (this.state.cardState == 'browse') {
				this.getPageData();
			}
		}
	}
	handleResultChange = (record, index, value) => {
		this.setState(state => {
			let workStartCheckVOS = state.workStartCheckVOS;
			workStartCheckVOS[index].qualification = value;
			return {
				workStartCheckVOS
			}
		});
	}
	setinstruction = (record, index, e) => {
		let value = e.target.value;
		this.setState(state => {
			let workStartCheckVOS = state.workStartCheckVOS;
			workStartCheckVOS[index].instruction = value;
			return {
				workStartCheckVOS
			}
		});
	}
	openUplad = () => {
		this.ygcUpload.open();
	}
	// 指派人选择
	handlerConfirmChooseApporea = (data) => {
		saveWrokStartReport(data, (res) => {
			let { resultCode, result, exMsg } = res.data;
			if (resultCode === 'ok') {
				this.setState({
					cardState: 'browse',
					pk: result.pkWorkstartreport,
				})
				this.props.approve.closeApproveModal();
			} else {
				this.props.approve.closeApproveModal();
				this.props.vendorsDanger({ text: exMsg });
			}
		});
	}
	// 审批、驳回
	handlePassReject = (data) => {
		setTimeout(() => {
			this.getPageData();
		}, 500);
		this.props.passreject.closePassRejectModal();
	}
	render() {
		return (
			<div className="ygc-card">
				<div className='ygc-card-header'>
					{this.props.YGCreateCardTitle({
						title: '开工报告',
						billIcon,
						backRoute: () => {
							if (window.sessionStorage.getItem('workstartreportListData')) {
								window.sessionStorage.setItem('workstartreportFromCardBrowse', 'true');
							}
							window.location.href = `./workstartreport.html#/list`;
						},
						pageStatus: this.state.cardState,
					})}
					<div className='ygc-card-header-button'>
						{this.props.YGCreateButton({
							btnTpl: btnCardTpl,
							buttonClick: buttonClick.bind(this)
						})}
					</div>
				</div>
				<div className="ygc-card-body">
					{this.props.YGCCreateForm({ ...this.formItems })}
					<div className="ygc-card-body-table-kgbg">
						<Table
							className='project_table'
							columns={this.columns}
							data={this.state.workStartCheckVOS}
							showRowNum={true}
							emptyText={() => '暂无数据'}
							rowKey='pkWorkqualitydetail'
							scroll={{ y: 500 }}
							bordered
						/>
					</div>
				</div>
				<YGCupload
					ref={(upload) => { this.ygcUpload = upload }}
					billType={'KGBG'}
					pkBill={this.state.formData.pkWorkstartreport}
					pkProject={this.state.formData.pkProject}
				/>
				{this.props.YGCreateApproveModal({ handlerConfirm: this.handlerConfirmChooseApporea })}
				{this.props.YGCreatePassRejectModal({ handlePassReject: this.handlePassReject })}
				{this.props.YGCreateAproHistoryModal({})}
			</div>
		)
	}
}

export default createYGCPage({})(WorkStartReportCard);